<template>
	<!--为echarts准备一个具备大小的容器dom-->
	<div class="body">
		<div class="left">
			<div id="main" style="width: 90%;height: 60vh"></div>
		</div>
		<div class="right" style="height: 60vh;">
			<el-date-picker
				v-model="value2"
				type="daterange"
				align="right"
				unlink-panels
				range-separator="至"
				start-placeholder="开始日期"
				end-placeholder="结束日期"
				:picker-options="pickerOptions">
			</el-date-picker>
			<button @click="dataSearch">查询</button>
			<div id="mychart" style="width: 90%;height: 57vh;margin-top: 2vh;"></div>
		</div>
		
	</div>
    
</template>
<script>
	export default {
		name: 'zhexiantu',
		data() {
			return {
				charts: '',
                //数据1
				opinionData1: [],
                //x轴
                age:[0,10,24,40,60,80,100],
				xData: ["0~10", "11~24","25~40","41~60","61~80","81~100"], //横坐标
                yData: [], //数据
				tableData:[],
				pickerOptions: {
					shortcuts: [{
						text: '最近一周',
						onClick(picker) {
						const end = new Date();
						const start = new Date();
						start.setTime(start.getTime() - 3600 * 1000 * 24 * 7);
						picker.$emit('pick', [start, end]);
						}
					}, {
						text: '最近一个月',
						onClick(picker) {
						const end = new Date();
						const start = new Date();
						start.setTime(start.getTime() - 3600 * 1000 * 24 * 30);
						picker.$emit('pick', [start, end]);
						}
					}, {
						text: '最近三个月',
						onClick(picker) {
						const end = new Date();
						const start = new Date();
						start.setTime(start.getTime() - 3600 * 1000 * 24 * 90);
						picker.$emit('pick', [start, end]);
						}
					}]
				},
				value2: '',
				time1:'',
				time2:'',
			}
		},
		created() {
            //页面加载进行获取数据
			this.getUserData();
			this.initYData();
		},
		methods: {
            getUserData(){
                this.$axios.post(
                    "/patient/selectAgeCount",
                    {
                        ages:this.age 
                    }
                ).then((res) => {
                    //赋值给y轴
                    this.opinionData1 = res.data;
                    //调用函数
                    this.$nextTick(function() {
                        //画div为main的数据
                        this.drawLine('main')
                    })
                }).catch(function(error) {
                    console.log(error);
                });

            },
			drawLine(id) {
                //初始化数据
				this.charts = this.$echarts.init(document.getElementById(id))
				this.charts.setOption({
					title: {
						text: '用户注册年龄统计图'
					},
                    //触发类型；轴触发，axis则鼠标hover到一条柱状图显示全部数据，item则鼠标hover到折线点显示相应数据
					tooltip: {
						trigger: 'axis'
					},
                    //所选项
					legend: {
						data: ['用户']
					},
                    //布局样式
					grid: {
						left: '3%',
						right: '4%',
						bottom: '3%',
						containLabel: true
					},
                    //下载图片按钮
					toolbox: {
						feature: {
							saveAsImage: {}
						}
					},
                    //x轴
					xAxis: {
						name: '(年龄)',
						type: 'category',
						boundaryGap: false,
						data: this.age

					},
                    //y轴
					yAxis: {
						name: '人数',
						type: 'value',
					},
					series: [
						{
							name: '用户',
							type: 'line',
							stack: '总人数',
							data: this.opinionData1
						}
					]
				});
				// 随着屏幕大小调节图表
                window.addEventListener("resize", () => {
                    this.charts.resize();
                });
			},
			initEcharts() {
                // 基本柱状图
                const option = {
                    title: {
                        text: '不同年龄段所花费的钱'
                    },
                    //触发类型；轴触发，axis则鼠标hover到一条柱状图显示全部数据，item则鼠标hover到折线点显示相应数据
                    tooltip: {
                        trigger: 'axis'
                    },
                    xAxis: {
                        name: '(类型)',
                        data: this.xData
                    },
                    yAxis: {
                        name: '金额(元)',
                    },
                    series: [
                        {
                            type: "bar", //形状为柱状图
                            data: this.yData
                        }
                    ]
                };
                const myChart = this.$echarts.init(document.getElementById("mychart"));
                myChart.setOption(option);
                // 随着屏幕大小调节图表
                window.addEventListener("resize", () => {
                    myChart.resize();
                });
            },
            async initYData(){
				// 将不同的年龄段传递给后端进行切割
				var age = '';
				for(var i = 0;i<this.xData.length;i++){
					//用,拼接
					if(i == this.xData.length-1){
						age = age + this.xData[i]
					}else{
						age = age + this.xData[i] +","
					}					
				}
				await this.$axios.get(
					"/patient/selectMoneyCount",
					{
						params:{
							age:age,
							time1:this.time1,
							time2:this.time2
						}
					}
				).then(res=>{
					if(res != undefined){
						this.yData = res.data
						console.log(111,this.yData)
					}
				})
				this.$nextTick(function() {
					//画div为mychart的数据
					this.initEcharts('mychart')
				})
                // })
            },
			dataSearch(){
				var time = this.value2.toString().split(",")
				var one = new Date(time[0])
				var two = new Date(time[1])
				this.time1 = this.formatDateTime(one)
				this.time2 = this.formatDateTime(two)
				this.initYData()
				
			},
			// 格式化时间
			formatDateTime(date) {  
				const year = date.getFullYear();  
				const month = String(date.getMonth() + 1).padStart(2, '0'); // 月份从0开始，需要加1  
				const day = String(date.getDate()).padStart(2, '0');  
				const hours = String(date.getHours()).padStart(2, '0');  
				const minutes = String(date.getMinutes()).padStart(2, '0');  
				const seconds = String(date.getSeconds()).padStart(2, '0');  
					
				return `${year}-${month}-${day} ${hours}:${minutes}:${seconds}`;  
			}  
  
		},

	}
</script>
<style scoped>
	* {
		margin: 0;
		padding: 0;
		list-style: none;
	}
	.body{
        display: flex; /* 使用Flexbox */  
        justify-content: space-between; /* 两端对齐，使左右两侧的内容尽量远离 */ 
        /* background-color: #e9e7e7; */
        /* background-size: 100% 100%; */
    }
	.left{
        margin: 15px;
		width: 50%;
    }
    .right{
		width: 50%;
        margin-right: 5%;
        background-color: white;
        box-shadow: 0 0 5px 5px #bababa;
        margin: 15px;
    }
	.right button{
		width: 60px;
		height: 30px;
		font-size: 14px;
		background-color: rgb(0, 85, 255);
		color:white;
		border: none;
		margin-left: 10px;
	}
	#main{
        /* margin-top: 2%; */
        /* float: left; */
        box-shadow: 0 0 5px 5px #bababa;
        background-color: white;
    }
</style>
